// $Id$
////////////////////////////////////////////////////////////////////////
// Purpose : Copy from stdin and paste to stdout
// DAte    : 2011.08.01
////////////////////////////////////////////////////////////////////////

#include <unistd.h>
#include <fcntl.h>
#include <string.h>

#define MAX_BUFF_SIZE 4096 // Max input size is 4KB

void WriteToStdout(const char *msg)
{
	size_t msg_len;
	ssize_t n;

	msg_len = strlen(msg);
	if( msg <= 0 )
		return;

	n = write(STDOUT_FILENO, msg, msg_len);
	if (n != msg_len)
	{
		return;
	}
}

void WriteToStderr(const char *msg)
{
	size_t msg_len;
	ssize_t n;

	msg_len = strlen(msg);
	if( msg <= 0 )
		return;

	n = write(STDERR_FILENO, msg, msg_len);
	if (n != msg_len)
	{
		return;
	}
}

void ReadFromStdinToStdout()
{
	char start_message[] = "The input is:\n";
	char end_message[] = "The input end.\n";
	char read_buffer[MAX_BUFF_SIZE];
	ssize_t n;
	size_t write_len;

	memset( read_buffer, 0, MAX_BUFF_SIZE );

	// Write some info messge to stdout
	WriteToStdout(start_message);
	
	n = read(STDIN_FILENO, read_buffer, MAX_BUFF_SIZE);
	if( n <= 0 )
	{
		WriteToStdout("read from stdin failed.\n");	
		return;
	}
	
	// Write some info messge to stdout
	WriteToStdout(end_message);

	// paste to stdout
	write_len = n;
	n = write(STDOUT_FILENO, read_buffer,write_len);
	if(n != write_len)
	{
		WriteToStderr("Write to stdout failed.\n");
		return;
	}

	return;
}

int main(int argc, char **argv)
{
	ReadFromStdinToStdout();
	return 1;
}
